import type { Router } from 'vue-router'
import { useAppStore } from '@/store'
import { getFormatDynamicRouter } from '@/utils/common/dynamic-router'

//首页
import home from '@/layout/index.vue'

/**
 * 添加动态路由/解决动态路由页面刷新白屏问题
 * @param router
 */
export default function useMenuListGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const app = useAppStore()
    app.getServicePermissionList()

    //判断pinia路由菜单数据是否存在
    if (app.serverMenu.length === 0) {
      //重新获取用户菜单
      await app.getServerMenuList()

      //处理后端菜单数据
      const data = await getFormatDynamicRouter(app.serverMenu)

      //console.log(data, '22222222222')

      //添加动态路由
      router.addRoute({
        path: '/',
        component: home,
        redirect: '/cvmagic/dashboard/workplace',
        children: data,
      })

      //等待路由加载完毕
      next({ ...to, replace: true })
    } else {
      next()
    }
  })
}
